package com.example.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.domain.Machine;
import com.example.domain.Order;
import com.example.domain.Pay;
import com.example.domain.Roll;
import com.example.exception.ServiceException;
import com.example.mapper.MachineMapper;
import com.example.service.MachineService;
import com.example.service.OrderService;
import com.example.service.RollService;
import com.example.service.UserService;
import com.example.util.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@CrossOrigin
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService service;

    @Autowired
    private UserService userService;

    @Autowired
    private MachineService machineService;

    @Autowired
    private RollService rollService;

    @GetMapping("/list")
    public R list(Order order) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(order.getOrderID() != null, Order::getOrderID, order.getOrderID());
        List<Order> list = service.list(wrapper);
        return R.data(list);
    }

    @PostMapping("/save")
    @Transactional
    public R save(@RequestBody Order order) {
        if (userService.getById(order.getSno()) == null) {
            return R.fail("学号不存在");
        }

        Machine machine = machineService.getByNumber(order.getMachineNumber());
        if (machine == null) {
            return R.fail("洗衣机编号不存在");
        }
        if (machine.getIdleStatus() == 1) {
            return R.fail("洗衣机被占用中");
        }

        machine.setIdleStatus(1);
        machineService.updateById(machine);

        order.setTotalCost(machine.getFloor() * 1.0);

        if (StrUtil.isBlank(order.getCouponCode())) {
            service.save(order);
            return R.success("操作成功");
        }

        Roll roll = rollService.getByCode(order.getCouponCode());
        if (roll == null) {
            throw new ServiceException("优惠券不存在");
        }

        if (!Objects.equals(roll.getSno(), order.getSno())) {
            throw new ServiceException("优惠券不属于该学生");
        }

        if (Objects.equals(roll.getUsed(), 1)) {
            throw new ServiceException("优惠券已被使用");
        }

        roll.setUsed(1);
        rollService.updateById(roll);

        order.setTotalCost(order.getTotalCost() * roll.getDiscount());
        service.save(order);
        return R.success("操作成功");
    }
}
